package com.weilele.mvvm.view

import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.weilele.mvvm.R
import com.weilele.mvvm.utils.activity.dip
import com.weilele.mvvm.widget.BaseFrameLayout
import kotlin.math.abs
import kotlin.math.max

/**
 * 描述：自动回顶部的RecyclerView
 */
class AutoTopRecyclerView : BaseFrameLayout {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    )

    //当滑动多少距离的时候显示回顶部按钮，单位dp
    private var showToTopButoonOffset = 1000

    //当滑动多少距离的时候，回底部不需要动画
    private var needShowToTopButoonOffset = 2000
    val rcv by lazy {
        RecyclerView(context)
    }
    val floatActionButton by lazy {
        FloatingActionButton(context)
    }
    private var onFloatButtonClickListener: Function1<FloatingActionButton, Unit>? = null

    init {
        addView(rcv, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
        rcv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //判断是否显示回顶部的floatBar
                    isShowActionButton()
                }
            }
        })
        floatActionButton.hide()
        floatActionButton.setImageResource(R.drawable.scroll_to_top)
        floatActionButton.size = FloatingActionButton.SIZE_MINI
        floatActionButton.setOnClickListener {
            if (getScroll() > dip(needShowToTopButoonOffset)) {
                rcv.scrollToPosition(0)
            } else {
                rcv.smoothScrollToPosition(0)
            }
            floatActionButton.hide()
            onFloatButtonClickListener?.invoke(floatActionButton)
        }
        addView(
            floatActionButton,
            LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT).apply {
                gravity = Gravity.END or Gravity.BOTTOM
                setMargins(0, 0, dip(16), dip(32))
            })
    }

    /**
     * 是否显示button
     */
    private fun isShowActionButton() {
        if (getScroll() > dip(showToTopButoonOffset)) {
            floatActionButton.show()
        } else {
            floatActionButton.hide()
        }
    }

    private fun getScroll(): Int {
        val x = abs(rcv.computeVerticalScrollOffset())
        val y = abs(rcv.computeHorizontalScrollOffset())
        return max(x, y)
    }
}